#include "bitstream.h"

void bitstream_init(struct bitstream *bst,unsigned char *pdata,unsigned int length)
{
    bst->pdata = pdata;
    bst->length = length;
    bst->pos_byte = 0;
    bst->pos_bit = 0;
}
unsigned char bitstream_read(struct bitstream *bst)
{
    unsigned char value = 0;

    if(bst->pos_byte < bst->length)
    {
        value = bst->pdata[bst->pos_byte] & (1<<(7-bst->pos_bit)) ? 1 : 0;
        bst->pos_bit++;
        if(bst->pos_bit >= 8)
        {
            bst->pos_byte++;
            bst->pos_bit = 0;
        }
    }
    return value;
}
void bitstream_write(struct bitstream *bst,unsigned char value)
{
    value = value ? 1 : 0;
    if(bst->pos_byte < bst->length)
    {
        bst->pdata[bst->pos_byte] = (bst->pdata[bst->pos_byte] & ~(1<<(7-bst->pos_bit))) | (value<<(7-bst->pos_bit));
        bst->pos_bit++;
        if(bst->pos_bit >= 8)
        {
            bst->pos_byte++;
            bst->pos_bit = 0;
        }
    }
}
